<template>
  <!-- 筛选 -->
  <base-search :title="t('keys.BasicInformation')" :isShowSearch="1"> </base-search>
  <div class="wrap">
    <el-col :span="10" style="min-width:600px">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="t('keys.avatar')" prop="username">
              <div class="headPortrait">{{ ruleForm.realName }}</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="t('keys.user_code')" prop="username">
              <el-input v-model="ruleForm.username" disabled style="width: 100%" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('keys.full_name')" prop="realName">
              <el-input v-model="ruleForm.realName" :disabled="!isEdit" style="width: 100%" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('keys.phone')" prop="phone" class="pofixd">
              <el-input
                v-model="ruleForm.phone"
                :placeholder="t('keys.pleaseEnter')"
                maxlength="11"
                oninput="value=value.replace(/[^\d]/g,'')"
                :disabled="!isEdit"
                style="width: 100%"
              >
                <template #prepend>
                  <el-select
                    v-model="ruleForm.telAreaCode"
                    :placeholder="t('keys.pleaseSelect')"
                    style="width: 80px"
                    clearable
                    :disabled="!isEdit"
                  >
                    <el-option v-for="(item, index) in formConfig.telAreaCodeObj.list" :label="item.valueCode" :value="item.valueCode" />
                  </el-select>
                </template>
              </el-input>
              <el-button type="primary" link @click="phonelValidate" class="poafixd" v-if="!isEdit && !ruleForm?.phoneCheckedFlag"
                >{{ t('keys.to_verify') }}
              </el-button>
              <el-button type="primary" link class="poafixdOk" v-else-if="!isEdit && ruleForm?.phoneCheckedFlag">
                <el-icon><CircleCheck /></el-icon>
                {{ t('keys.verified') }}
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('keys.email')" prop="email" class="pofixd">
              <el-input
                v-model="ruleForm.email"
                :placeholder="t('keys.pleaseEnter')"
                maxlength="60"
                style="width: 100%"
                :disabled="!isEdit"
              ></el-input>
              <el-button type="primary" link @click="getEmailValidate" class="poafixd" v-if="!isEdit && !ruleForm?.emailCheckedFlag">
                {{ t('keys.to_verify') }}
              </el-button>
              <el-button type="primary" link @click="getEmailValidate" class="poafixd poafixdOk" v-else-if="!isEdit && ruleForm?.emailCheckedFlag">
                <el-icon><CircleCheck /></el-icon>
                {{ t('keys.verified') }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="t('keys.gender')" prop="gender">
              <el-select v-model="ruleForm.gender" :placeholder="t('keys.pleaseSelect')" style="width: 100%" :disabled="!isEdit">
                <el-option v-for="(item, index) in formConfig.genderObj.list" :label="item.valueContent" :value="item.valueCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('keys.birthday')" prop="birthday">
              <el-date-picker
                style="width: 100%"
                v-model="ruleForm.birthday"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                :placeholder="t('keys.please_select_date_tips')"
                :disabled-date="disabledDate"
                :disabled="!isEdit"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="t('keys.locale')" prop="locale">
              <el-select
                class="smsinput"
                style="width: 100%"
                v-model="ruleForm.locale"
                :placeholder="t('keys.pleaseSelect')"
                :disabled="!isEdit"
              >
                <el-option
                  v-for="item in formConfig.localeObj.list"
                  :key="item.valueCode"
                  :label="item.valueContent"
                  :value="item.valueCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 编辑 -->
            <el-button type="info" v-if="!isEdit" @click="isEdit = !isEdit">{{ t('keys.edit') }}</el-button>
            <!-- 取消 -->
            <el-button type="info" v-if="isEdit" @click="isEdit = !isEdit">{{ t('keys.cancel') }}</el-button>
            <!-- 确定 -->
            <el-button type="primary" :loading="btnLoading" @click="submitForm(ruleFormRef)" v-if="isEdit">{{ t('keys.ok') }}</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-col>
  </div>

  <zcb-dialog
    v-model="showPhoneDialog"
    :title="t('keys.phone_verification')"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <template #btns>
      <el-button @click="resetForm(formRef)">{{ t('keys.cancel') }}</el-button>
      <el-button type="primary" @click="submitCode(formRef)">{{ t('keys.ok') }}</el-button>
    </template>
    <el-form ref="formRef" :model="phoneForm" label-width="100px">
      <el-form-item :label="t('keys.phone')" prop="lang">
        {{ ruleForm.phone }}
      </el-form-item>
      <el-form-item
        :label="t('keys.Verification_Code')"
        prop="code"
        :rules="[
          { required: true, message: t('keys.Please_enter_the_verification_code') },
          { type: 'number', message: t('keys.Incorrect_input_of_verification_code') }
        ]"
      >
        <el-input v-model.number="phoneForm.code" type="text" autocomplete="off" maxlength="8">
          <template #append>
            <el-button type="primary" :disabled="btnCode.disabled" @click="getCode">{{ btnCode.btnTxt }}</el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </zcb-dialog>
</template>

<script setup>
import { reactive, ref, onMounted, watch, unref } from 'vue'
import {
  getLovValueInfoApi,
  getUserInfoApi,
  putUserInfoApi,
  getEmailValidateApi,
  getPhoneValidateApi,
  postPhoneValidateApi,
  postUpdatePasswordApi
} from 'api/home'
// import ThemePicker from 'components/ThemePicker/index.vue'
import { ERR_OK } from 'config/statusCode'
import { ElMessage, ElMessageBox } from 'element-plus'
import { validateEmail, validatePhone, validPasswordNew } from 'utils/validate.js'
// import ZcbSearch from 'components/zcb-search'
import { useI18n } from 'vue-i18n'
const { t } = useI18n() // 中英文
const formSize = ref('default')
const showPhoneDialog = ref(false)
const showPwdDialog = ref(false)
const ruleFormRef = ref(null)
const btnLoading = ref(false)
const formRef = ref(null)

const isEdit = ref(false)
const btnConfig = defineProps({
  clickbtn: {
    type: Boolean,
    default: false
  }
})
const ruleForm = ref({
  username: '', // 用户编码
  realName: '', // 用户姓名
  telAreaCode: '+86', // 电话区号。
  phone: '', // 手机号
  email: '', // 邮箱
  gender: '1', // 用户性别:1:男 2:女 3未知
  birthday: '', // 出生日期
  locale: '', // 地区
  lang: '' // 语言
})
const phoneForm = ref({
  code: '',
  telephone: ''
})

const btnCode = reactive({
  btnTxt: t('keys.Get_verification_code'), //获取验证码
  disabled: false,
  time: 0
})
const checkPhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t('keys.phone_cant_empty')))
  }
  setTimeout(() => {
    if (!Number.isInteger(+value)) {
      callback(new Error(t('keys.please_enter_number_tips')))
    } else {
      if (validatePhone(value)) {
        callback()
      } else {
        callback(new Error(t('keys.reg_tele_empty_format_tips')))
      }
    }
  }, 100)
}
const checkEmail = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t('keys.email_cant_empty')))
  }
  setTimeout(() => {
    if (validateEmail(value)) {
      callback()
    } else {
      callback(new Error(t('keys.Email_format_error')))
    }
  }, 100)
}
const rules = reactive({
  realName: [{ required: true, message: t('keys.Please_enter_the_employee_name'), trigger: 'blur' }],
  phone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
  email: [{ required: true, validator: checkEmail, trigger: 'blur' }]
})

const formConfig = reactive({
  telAreaCodeObj: {
    // 电话区号列表list
    list: [],
    Params: {
      lovCode: 'ZIAM.AREA_CODE', // ZTNT.LOV_TYPE
      tag: '' // 特殊标记
    }
  },
  genderObj: {
    // 用户性别list
    list: [],
    Params: {
      lovCode: 'ZIAM.GENDER', // ZTNT.LOV_TYPE
      tag: '' // 特殊标记
    }
  },
  officeObj: {
    // 任职状态list
    list: [],
    Params: {
      lovCode: 'ZIAM.OFFICE_TYPE', // ZTNT.LOV_TYPE
      tag: '' // 特殊标记
    }
  },
  localeObj: {
    // 下拉地区list
    list: [],
    Params: {
      lovCode: 'ZIAM.LOCALE', // ZTNT.LOV_TYPE
      tag: '' // 特殊标记
    }
  },
  langObj: {
    // 语言
    list: [],
    Params: {
      lovCode: 'ZIAM.LANG', // ZTNT.LOV_TYPE
      tag: '' // 特殊标记
    }
  }
})
// 提交保存
const submitForm = async (ruleFormRef) => {
  if (!ruleFormRef) return
  btnLoading.value = true
  await ruleFormRef.validate((valid, fields) => {
    if (valid) {
      putUserInfo()
    } else {
    }
    btnLoading.value = false
  })
}
const getEmailValidate = () => {
  const { code } = getEmailValidateApi()
  if (code === ERR_OK) {
  }
  ElMessageBox.alert(t('keys.mail_sent'), t('keys.mailbox_verification'), {
    confirmButtonText: t('keys.ok'),
    showClose: 'false',
    callback: (action) => {
      // ElMessage({
      //   type: 'success',
      //   message: `邮件发送成功`
      // })
    }
  })
}
const phonelValidate = () => {
  showPhoneDialog.value = true
}
// 获取验证码
const getCode = async () => {
  const { code } = await getPhoneValidateApi()
  if (code === ERR_OK) {
    ElMessage({
      message: t('keys.Verification_code_sent'),
      type: 'success'
    })
    btnCode.time = 30 //设置倒计时的时间（单位秒）
    btnCode.disabled = true
    timer() //调用倒计时方法
  }
}
//倒计时方法
const timer = () => {
  if (btnCode.time > 0) {
    btnCode.time--
    btnCode.btnTxt = btnCode.time + t('keys.Reacquire_the_verification_code_after') //s后重新获取验证码
    setTimeout(timer, 1000)
  } else {
    btnCode.time = 0
    btnCode.btnTxt = t('keys.Get_verification_code')
    btnCode.disabled = false
  }
}
// 提交手机验证
const submitCode = async (ruleFormRef) => {
  if (!ruleFormRef) return
  await ruleFormRef.validate(async (valid, fields) => {
    if (valid) {
      // putUserInfo()
      const params = { ...phoneForm.value }
      const { code, desc } = await postPhoneValidateApi(params)
      if (code === ERR_OK) {
        ElMessage({
          message: t('keys.Validation_succeeded'),
          type: 'success'
        })
        showPhoneDialog.value = false
      } else {
        ElMessage({
          message: desc,
          type: 'warning'
        })
      }
    } else {
    }
  })
}
// 修改用户信息
const putUserInfo = async () => {
  const params = { ...ruleForm.value }
  const { code } = await putUserInfoApi(params, JSON.parse(localStorage.getItem('userinfo'))['userId'])
  if (code === ERR_OK) {
    ElMessage({
      message: t('keys.modified'),
      type: 'success'
    })
    isEdit.value = false
    getUserInfo()
  }
}
// 获取用户信息
const getUserInfo = async () => {
  const { code, data } = await getUserInfoApi({}, JSON.parse(localStorage.getItem('userinfo'))['userId'])
  if (code === ERR_OK) {
    ruleForm.value = { ...data }
    phoneForm.value.telephone = data.phone
    ruleForm.value.gender = ruleForm.value.gender.toString()
  }
}
// 获取字典
const getLovValueInfo = async (key) => {
  const params = formConfig[key].Params
  const { code, data } = await getLovValueInfoApi(params)
  if (code === ERR_OK) {
    formConfig[key].list = data
  }
}
const handleClose = () => {}

// 重置参数
const resetForm = (ruleFormRef) => {
  if (!ruleFormRef) return
  const form = unref(ruleFormRef)
  form.resetFields()
  showPwdDialog.value = false
  showPhoneDialog.value = false
}
const disabledDate = (time) => {
  return time.getTime() > Date.now() - 8.64e6
}
onMounted(() => {
  getLovValueInfo('telAreaCodeObj')
  getLovValueInfo('genderObj')
  getLovValueInfo('localeObj')
  getLovValueInfo('langObj')
  getUserInfo()
})
</script>

<style lang="scss" scoped>
.wrap {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.headPortrait {
  width: 60px;
  height: 60px;
  background: var(--el-color-primary-light-5);
  border-radius: 50%;
  text-align: center;
  line-height: 60px;
  color: #ffffff;
}
.demo-ruleForm {
  :deep(.el-form-item__content) {
    justify-content: space-between;
  }
}
.pofixd {
  position: relative;
  .poafixd {
    position: absolute;
    right: 10px;
    color: #0066ff;
  }
  .poafixdOk {
    color: #00b42a;
    position: absolute;
    right: 10px;
  }
}
</style>
